package china.lzy.service.impl;

import china.lzy.dao.ShopMapper;
import china.lzy.entity.ResCode;
import china.lzy.entity.ResResult;
import china.lzy.entity.dto.PageDto;
import china.lzy.entity.pojo.Shop;
import china.lzy.exception.ParamErrorException;
import china.lzy.service.ShopService;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {

    @Resource
    private ShopMapper shopDao;


    @Override
    public ResResult insert(Shop shop) {
        // valid
        if (shop == null) {
            throw new ParamErrorException("缺少必要参数");
        }
        if (ObjectUtil.isNull(shop.getCreateTime())) {
            shop.setCreateTime(new Date());
        }
        shopDao.insert(shop);
        return new ResResult(ResCode.SAVE_OK);
    }


    @Override
    public ResResult delete(int id) {
        int ret = shopDao.delete(id);
        return ret > 0 ? ResResult.ResResultBuilder(ResCode.DELETE_OK) : ResResult.ResResultBuilder(ResCode.OPERATE_ERROR);
    }


    @Override
    public ResResult update(Shop shop) {
        int ret = shopDao.update(shop);
        return ret > 0 ? ResResult.ResResultBuilder(ResCode.OPERATE_OK) : ResResult.ResResultBuilder(ResCode.OPERATE_ERROR);
    }


    @Override
    public ResResult load(int id) {
        Shop load = shopDao.load(id);

        return ResResult.ResResultBuilder(load, ResCode.OPERATE_OK);
    }


    @Override
    public ResResult pageList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<Shop> shops = shopDao.pageList();
        PageInfo pageInfo = new PageInfo<>(shops);
        pageDto.setRecords(shops);
        pageDto.setTotal((int) pageInfo.getTotal());
        return ResResult.ResResultBuilder(pageDto, ResCode.OPERATE_OK);
    }

}